import os
import re
import datetime
from exemgut import load_yml, exe_cmd

def get_match_result(pattern, text):
    matches = re.search(pattern, text)
    if not matches:
        return 0
    else:
        return int(matches.group(1))


def get_pytest_log_result(log):
    with open(log, 'r') as f:
        data = f.read()
    n_passed = get_match_result(r'=+.+ (\d+) passed.+ in .+ =+', data)
    n_failed = get_match_result(r'=+.+ (\d+) failed.+ in .+ =+', data)
    n_error = get_match_result(r'=+.+ (\d+) error.+ in .+ =+', data)
    n_collected = get_match_result(r'.+collected (\d+) items.+', data)
    return n_passed, n_failed, n_error, n_collected


if __name__ == '__main__':
    log_root = './logs/utlogs'
    log_dir_name = max([x for x in os.listdir(log_root) if os.path.isdir(os.path.join(log_root, x))])
    log_dir_path = os.path.join(log_root, log_dir_name)
    logs = os.listdir(log_dir_path)
    passed_cnt, failed_cnt = 0, 0
    failed_list = []
    for log in logs:
        log = os.path.join(log_dir_path, log)
        n_passed, n_failed, n_error, n_collected = get_pytest_log_result(log)
        if (not (n_failed or n_error)) and (n_passed or n_collected == 0):
            passed_cnt += 1
        else:
            failed_cnt += 1
            failed_list.append(log)
    failed_list.sort()
    cmds = load_yml('commands.yml')
    ignores_cnt = len(cmds['ignores'])
    res_str = '\n'.join([f"{datetime.date.today().strftime('%Y%m%d')}",
                         f"ut passed: {passed_cnt}", f"ut ignores: {ignores_cnt}",
                         f"ut failed: {failed_cnt}", '----------failed cases:----------'] + failed_list)
    res_path = f'./logs/utresult/{log_dir_name}.txt'
    if not os.path.exists(os.path.dirname(res_path)):
        os.makedirs(os.path.dirname(res_path))
    with open(res_path, 'w') as f:
        f.write(res_str)
    res_path2 = res_path.replace(log_dir_name, 'ut_result')
    exe_cmd(f"cp -rf {res_path} {res_path2}")
    print(f"ut passed: {passed_cnt}; ut ignores: {ignores_cnt}; ut failed: {failed_cnt}")
